from django.http import HttpResponse
from django.views import View
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from book.models import BookInfo
from book.serializers_2 import BookSerializer
from rest_framework.decorators import action
from django.urls import reverse


class BookViewSet(ModelViewSet):
    queryset = BookInfo.objects.all()
    serializer_class = BookSerializer

    def list(self, request):
        return super().list(request)

    @action(methods=['get'], detail=False)
    def latest(self, request):
        """
        返回最新的图书信息
        """
        book = BookInfo.objects.latest('id')
        serializer = self.get_serializer(book)
        return Response(serializer.data)

    @action(methods=['put'], detail=True)
    def read(self, request, pk):
        """
        修改图书的阅读量数据
        """
        book = self.get_object()
        book.bread = request.data.get('read')
        book.save()
        serializer = self.get_serializer(book)
        return Response(serializer.data)

    @action(methods=['get'], detail=False)
    def test(self, request):
        # path = reverse('book-list') # "/books/"
        # path = reverse('book-test') # "/books/test/"
        path = reverse('book-latest') # "/books/latest/"

        # ref: https://www.django-rest-framework.org/api-guide/routers/
        # basename 是book，作用是确定url名字，url名字的作用可以通过reverse来确定
        # 导包路径 from django.urls import reverse

        return Response(path)

